﻿using EnglishAuction.BUS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace EnglishAuction
{
    public partial class DetailsProduct : System.Web.UI.Page
    {
        protected int Id { get; set; }
        protected string JsonDate { get; set; }
        protected NguoiThangCuoc ntc;

        private void RefreshCaptcha()
        {
            string text = (Guid.NewGuid().ToString()).Substring(0, 5);
            Response.Cookies["Captcha"]["value"] = text;
            imgcaptcha.ImageUrl = "captcha.aspx";
        }

        private void CheckUserLike()
        {
            if (Session["CurrentUser"] == null)
            {
                btnLike.Text = "like";
                imageLike.ImageUrl = "images/like.png";
            }
            else
            {
                NguoiDung nguoiDung = Session["CurrentUser"] as NguoiDung;
                if (ChiSoLikeBUS.Check(Id, nguoiDung.Id))
                {
                    btnLike.Text = "unlike";
                    imageLike.ImageUrl = "images/unlike.png";
                }
                else
                {
                    btnLike.Text = "like";
                    imageLike.ImageUrl = "images/like.png";
                }
            }
        }

        private void ShowLike()
        {
            int count = ChiSoLikeBUS.Count(Id);
            txtSoNguoiLike.Text = count == 0 ? "" : "+" + count.ToString();
        }

        private void ShowListDauGia()
        {
            var lst = DauGiaBUS.GetListBySanPhamId(Id);
            //lst = lst.Concat(lst).Concat(lst).Concat(lst).Concat(lst).Concat(lst).Concat(lst).Concat(lst).Concat(lst).ToList();
            gvDanhSachDauGia.DataSource = lst;
            gvDanhSachDauGia.DataBind();
        }

        private void Rating()
        {
            ntc = SanPhamBUS.GetIdUserRating(Id);
            if (ntc != null)
            {
                this.panelRating.Visible = true;
                this.rating.CurrentRating = ntc.Rating ?? 0;
                NguoiDung nguoiDung = Session["CurrentUser"] as NguoiDung;
                if (nguoiDung != null)
                {
                    if (nguoiDung.Id == ntc.NguoiDungId)
                        this.rating.ReadOnly = false;
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["Id"] != null)
            {
                int id = int.Parse(Request.QueryString["Id"]);
                if (id > 0)
                {
                    Id = id;
                    Rating();
                    GetComment();
                    ShowLike();
                    CheckUserLike();
                    ShowListDauGia();

                    List<SanPham> list = new List<SanPham>();
                    var sanPham = SanPhamBUS.GetById(id);
                    var deadline = sanPham.NgayLenSan.Value.AddDays((double)sanPham.ThoiGianDauGia);
                    JsonDate = String.Format("{0:MMMM dd, yyyy HH:mm:ss}", deadline);
                    sanPham.Countdown = "<div id='txtCountdown'></div>";
                    list.Add(sanPham);
                    fvSanPhamDauGia.DataSource = list;
                    fvSanPhamDauGia.DataBind();

                    // Mô tả sản phẩm
                    List<SanPham> listProduct = new List<SanPham>();
                    listProduct.Add(SanPhamBUS.GetById(id));
                    fvMoTa.DataSource = listProduct;
                    fvMoTa.DataBind();
                    if (!Page.IsPostBack)
                    {
                        panelDauGia.Visible = false;
                        RefreshCaptcha();
                    }
                    txtGiaDau.Attributes.Add("onkeypress", "return isNumberKey(event)");
                }
            }
            else
            {
                Response.Redirect("Default.aspx");
            }

        }

        protected void fvSanPhamDauGia_PageIndexChanging(object sender, FormViewPageEventArgs e)
        {

        }

        protected void btnComment_Click(object sender, EventArgs e)
        {
            if (Session["CurrentUser"] == null)
            {
                string script = "$(function(){openDialog();setError('Bạn hãy đăng nhập để thực hiện chức năng này.')});";
                ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "dialog", script, true);
                return;
            }
            
            if (txtContent.Text.Trim().Equals(""))
                return;
            var userCurrent = Session["CurrentUser"] as NguoiDung;
            Comment comment = new Comment();
            comment.NguoiDungId = userCurrent.Id;
            comment.NoiDung = txtContent.Text;
            comment.SanPhamId = Id;
            comment.NgayTao = DateTime.Now;
            CommentBUS.Insert(comment);
            GetComment();
            txtContent.Text = "";
        }

        private void GetComment()
        {
            dataListComment.DataSource = CommentBUS.GetByProductId(Id);
            dataListComment.DataBind();
        }

        protected void dataListComment_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            Label tenNguoiDung = e.Item.FindControl("labelTenNguoiDung") as Label;
            tenNguoiDung.Text = NguoiDungBUS.GetById(int.Parse(tenNguoiDung.Text)).HoTen;
        }

        protected void btnLike_Click(object sender, EventArgs e)
        {
            if (Session["CurrentUser"] == null)
            {
                string script = "$(function(){openDialog();setError('Bạn hãy đăng nhập để thực hiện chức năng này.')});";
                ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "dialog", script, true);
                return;
            }

            if (btnLike.Text.Equals("like"))
            {
                ChiSoLike chisolike = new ChiSoLike();
                chisolike.SanPhamId = Id;
                chisolike.NguoiDungId = (Session["CurrentUser"] as NguoiDung).Id;
                ChiSoLikeBUS.Insert(chisolike);
                int count = ChiSoLikeBUS.Count(Id);
                txtSoNguoiLike.Text = count == 0 ? "" : "+" + count.ToString();
                btnLike.Text = "unlike";
                imageLike.ImageUrl = "images/unlike.png";
            }
            else
            {
                ChiSoLikeBUS.Delete(Id, (Session["CurrentUser"] as NguoiDung).Id);
                int count = ChiSoLikeBUS.Count(Id);
                txtSoNguoiLike.Text = count == 0 ? "" : "+" + count.ToString();
                btnLike.Text = "like";
                imageLike.ImageUrl = "images/like.png";
            }
        }

        protected void btnStartAuction_Click(object sender, EventArgs e)
        {
            panelDauGia.Visible = !panelDauGia.Visible;
        }

        protected void gvDanhSachDauGia_DataBound(object sender, EventArgs e)
        {

        }

        protected void gvDanhSachDauGia_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItem != null)
            {
                string value = e.Row.Cells[1].Text;
                e.Row.Cells[1].Text = "&nbsp;" + NguoiDungBUS.GetById(int.Parse(value)).HoTen;
            }
        }

        protected void timer_Tick(object sender, EventArgs e)
        {
            ShowListDauGia();
        }

        protected void btnDauGia_Click(object sender, EventArgs e)
        {
            RefreshCaptcha();
            if (Session["CurrentUser"] == null)
            {
                string script = "$(function(){openDialog();setError('Bạn hãy đăng nhập để tham gia đấu giá.')});";
                ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "dialog", script, true);
                return;
            }


            NguoiDung nguoiDung = Session["CurrentUser"] as NguoiDung;
            if (nguoiDung != null && nguoiDung.LoaiNguoiDungId == 2)
            {
                if (txtCaptcha.Text.ToString() != Request.Cookies["Captcha"]["value"])
                {
                    string script = "$(function(){openDialog();setError('Mã bảo vệ không đúng.')});";
                    ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "dialog", script, true);
                }
                else
                {
                    if (txtGiaDau.Text.Equals(""))
                    {
                        string script = "$(function(){openDialog();setError('Giá đấu chưa được nhập.')});";
                        ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "dialog", script, true);
                        return;
                    }
                    var dauGiaMax = DauGiaBUS.GetGiaDauMax(Id);
                    var giaDau = Utilities.Currency(txtGiaDau.Text);
                    bool validate = true;

                    if (dauGiaMax == null)
                    {
                        if (giaDau <= SanPhamBUS.GetById(Id).GiaSan || giaDau % 50000 != 0)
                            validate = false;
                    }
                    else
                    {
                        if (giaDau <= dauGiaMax.GiaHienTai || giaDau % 50000 != 0)
                            validate = false;
                    }

                    if (!validate)
                    {

                        string script = "$(function(){openDialog();setError('Giá đấu không hợp lệ.')});";
                        ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "dialog", script, true);
                    }
                    else
                    {

                        DauGia dauGia = new DauGia();
                        dauGia.GiaHienTai = giaDau;
                        dauGia.NguoiDungId = nguoiDung.Id;
                        dauGia.SanPhamId = Id;
                        dauGia.ThoiGian = DateTime.Now;
                        DauGiaBUS.Insert(dauGia);
                        var nguoiThangCuoc = NguoiThangCuocBUS.CheckExist(Id);
                        if (nguoiThangCuoc != null)
                            NguoiThangCuocBUS.Delete(nguoiThangCuoc.Id);
                        NguoiThangCuoc ntc = new NguoiThangCuoc();
                        ntc.NguoiDungId = nguoiDung.Id;
                        ntc.SanPhamId = Id;
                        ntc.Gia = giaDau;
                        ntc.ThanhToan = 0;
                        ntc.ThoiGian = DateTime.Now;
                        NguoiThangCuocBUS.Insert(ntc);

                        ShowListDauGia();
                        txtCaptcha.Text = "";
                        txtGiaDau.Text = "";

                        SanPham sp = SanPhamBUS.GetById(Id);

                        if (sp.CongThem == null)
                        {
                            if (sp.NgayLenSan.Value.AddDays(sp.ThoiGianDauGia.Value).AddMinutes(5) > DateTime.UtcNow)
                            {
                                sp.CongThem = 2;
                                sp.NgayLenSan.Value.AddMinutes(5);
                                SanPhamBUS.Update(sp);
                            }
                        }
                    }
                }
            }
            else
            {
                string script = "$(function(){openDialog();setError('Tài khoản của bạn không thể tham gia đấu giá.')});";
                ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "dialog", script, true);
            }

        }

        protected void fvSanPhamDauGia_ItemCreated(object sender, EventArgs e)
        {
            /*var sanPham = SanPhamBUS.GetById(Id);
             if (sanPham == null)
                 return;
             if (sanPham.NgayLenSan.Value.AddDays((double)sanPham.ThoiGianDauGia).CompareTo(DateTime.Now) <= 0)
             {
                 Button btnThamGiaDauGia = fvSanPhamDauGia.FindControl("btnStartAuction") as Button;
                 if (btnThamGiaDauGia != null)
                 {
                     btnThamGiaDauGia.Text = "Sản phẩm đã hết hạn đấu giá";
                     btnThamGiaDauGia.Enabled = false;
                 }
             }*/
        }

        protected void rating_Changed(object sender, AjaxControlToolkit.RatingEventArgs e)
        {
            if (ntc != null)
            {
                NguoiThangCuocBUS.UpdateRating(ntc.Id, int.Parse(e.Value));
            }
        }
    }
}